package com.tonels;

import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 过滤 图片 ，XML，删除无关 文件
 */
public class JpgId {

    private static final Logger logger = LoggerFactory.getLogger(JpgId.class);


    public static final String PATH_Target = "\\\\192.168.1.74\\public\\testts\\all-0707\\data7\\test\\liangshuai";

    public static final Set<Integer> picIDs = Sets.newTreeSet((o1, o2) -> o1.compareTo(o2));
    public static final Set<Integer> xmlIDs = Sets.newTreeSet((o1, o2) -> o1.compareTo(o2));

    public static void main(String[] args) throws IOException {

        Path startingDir = Paths.get(PATH_Target);
        Files.walkFileTree(startingDir, new FindJavaVisitor());

        Set<Integer> collect = picIDs.stream().filter(e -> !xmlIDs.contains(e)).sorted().collect(Collectors.toCollection(LinkedHashSet::new));

        logger.info("图片ID：{}个,包括{},xmlID：{}个,包括{},无XML的图片ID:{}个,包括{}", picIDs.size(), picIDs, xmlIDs.size(), xmlIDs, collect.size(), collect);

        Set<Integer> collect1 = xmlIDs.stream().filter(e -> !picIDs.contains(e)).sorted().collect(Collectors.toCollection(LinkedHashSet::new));
        System.out.println(collect1);

        // 图片过滤删除
//        Files.walkFileTree(startingDir, new delJavaVisitor(collect));
    }

    private static class FindJavaVisitor extends SimpleFileVisitor<Path> {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            File file1 = file.toFile();
            String name = file1.getName();
            if (name.endsWith(".jpg")) {
                String substring = name.substring(0, name.length() - 4);
                picIDs.add(Integer.valueOf(substring));
            } else if (name.endsWith(".xml")) {
                String substring = name.substring(0, name.length() - 4);
                xmlIDs.add(Integer.valueOf(substring));
            }
            return FileVisitResult.CONTINUE;
        }
    }

    private static class delJavaVisitor extends SimpleFileVisitor<Path> {
        private Set<Integer> lists;
        public delJavaVisitor(Set<Integer> collect) {
            this.lists = collect;
        }
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            File file1 = file.toFile();
            String name = file1.getName();
            String nameNoJpg = name.substring(0, name.length() - 4);
            if (name.endsWith(".jpg") && lists.contains(Integer.valueOf(nameNoJpg))) {
                Files.delete(file);
                logger.info("删除成功，文件:{}", name);
            }
            return FileVisitResult.CONTINUE;
        }
    }


}
